import datetime
import logging

import pymongo

from base.connection import mongodb_util
from base.request import ApiBaseHandler
from common.definition import ret_msg
from helper.api_helper import ApiHelper
from helper.payment.pay_util import generator_trade_no

logger = logging.getLogger("wechat.handlers.restaurant")


class RestaurantInfo(ApiBaseHandler):
    async def get(self):
        # 特别为香榭里活动的代码 >>>
        address_info = []
        address = dict(
            id="1",
            name="香榭里音乐餐厅",
            address="深圳市龙华新区民治大道286号三楼",
            area="龙华",
            type="音乐餐厅",
            tel="18033403930",
            areaCode="",
            lat=22.621860,
            lng=114.039750
        )

        address_info.append(address)
        context = dict(addresses=address_info, count=len(address_info))
        return self.write(ret_msg(data=context))

        # 原来的代码 >>>
        page_index = self.get_argument("page_index", None)
        page_size = self.get_argument("page_size", None)
        try:
            db = mongodb_util.db
            if page_index and page_size:
                page_index = int(page_index)
                page_size = int(page_size)
                ApiHelper.inspect_common_params(page_index, page_size)
                page_start = page_index * page_size
                addresses = db.sdec_restaurant_address.find({
                    "is_delete": False
                }).sort("id", pymongo.DESCENDING).skip(page_start).limit(page_size)
            else:
                addresses = db.sdec_restaurant_address.find({"is_delete": False}).sort("id", pymongo.DESCENDING)
        except Exception as e:
            logger.error(e)
            return self.write(ret_msg(code=-1, error_message="系统繁忙, 请稍后重试!"))
        count = addresses.count()
        address_info = []
        for a in addresses:
            address = dict(
                id=a["id"],
                name=a["name"],
                address=a["address"],
                area=a["area"],
                type=a["type"],
                tel=a["tel"],
                areaCode=a["areaCode"],
                lat=a["lat"],
                lng=a["lng"]
            )
            address_info.append(address)
        context = dict(addresses=address_info, count=count)
        return self.write(ret_msg(data=context))

    async def post(self):
        open_id = await self.get_open_id()
        oid_list = ["o7qyl0vKx54jB05FjmxNw76SJAPE", "o7qyl0kQ11-oF9RV6__m6t1JVpDk", "o7qyl0o2pUndsCkpeq62JnFdQ0OI"]
        if open_id not in oid_list:
            return self.write(ret_msg(code=-1, error_message="没有地址录入权限!"))
        name = self.get_argument("name", None)  # 餐厅名称
        address = self.get_argument("address", None)  # 餐厅地址
        area = self.get_argument("area", None)  # 餐厅所属区: 如宝安区
        type = self.get_argument("type", None)  # 餐厅主营菜系: 如湘菜
        tel = self.get_argument("tel", None)  # 餐厅负责人手机号码
        areaCode = self.get_argument("areaCode", None)  # 区号
        lat = self.get_argument("lat", None)  # 纬度
        lng = self.get_argument("lng", None)  # 经度
        if not all((name, address, area, lat, lng)):
            return self.write(ret_msg(code=-1, error_message="缺少请求参数"))
        data = dict(
            name=name,
            address=address,
            area=area,
            type=type,
            tel=tel,
            areaCode=areaCode,
            lat=lat,
            lng=lng,
            is_delete=False,
            id=generator_trade_no(),
            create_time=datetime.datetime.now(),
            update_time=datetime.datetime.now()
        )
        try:
            db = mongodb_util.db
            db.sdec_restaurant_address.insert(data)
        except Exception as e:
            logger.error(e)
            return self.write(ret_msg(code=-1, error_message="餐厅信息录入失败, 请稍后重试!"))
        return self.write(ret_msg())


class DeleteRestaurantInfo(ApiBaseHandler):
    async def get(self):
        auth_user = "o7qyl0vKx54jB05FjmxNw76SJAPE"
        open_id = await self.get_open_id()
        id = self.get_argument("id", None)
        if open_id != auth_user:
            return self.write(ret_msg(code=-1, error_message="没有权限，请联系管理员!"))
        if not id:
            return self.write(ret_msg(code=-1, error_message="请求参数错误!"))
        data = {"id": id}
        try:
            db = mongodb_util.db
            db.sdec_restaurant_address.delete_one(data)
        except Exception as e:
            logger.error(e)
            return self.write(ret_msg(code=-1, error_message="删除餐厅信息失败!"))
        return self.write(ret_msg())
